package com.shcowin.controller;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shcowin.biz.AccountBiz;
import com.shcowin.entity.Account;

@Controller
@RequestMapping("/admin")
public class AdminController{
    
    @Inject
    private AccountBiz<Account> biz;
    
    @RequestMapping("/login")
    @ResponseBody
    public Map<String,Object> login(String username,String password,HttpServletRequest request,HttpServletResponse response) {
    	boolean valiRes = validate(username,password);
    	if(valiRes){
    		request.getSession().setAttribute("username", username);
    	}
    	Map<String,Object> json = new HashMap<String,Object>();
    	json.put("result", valiRes);
    	return json;
    }
    
    @RequestMapping("/loginOut")
    @ResponseBody
    public Map<String,Object> loginOut(HttpServletRequest request) {
    	request.getSession().removeAttribute("username");
    	Map<String,Object> json = new HashMap<String,Object>();
    	json.put("result", true);
    	return json;
    }
    
    private boolean validate(String username,String password){
    	Account account = biz.getByUsername(username);
    	if(null == account){
    		return false;
    	}
    	if(username.equals(account.getUsername()) && password.equals(account.getPassword())){
    		return true;
    	}
    	return false;
    }
}
